import {
  Controller,
  Post,
  Body,
  Req,
  Get,
  Query,
  Delete,
  ParseBoolPipe,
} from '@nestjs/common';
import { Request } from 'express';
import { MenuService } from './menu.service';
import { SaveMenuDto } from './dto/menu.dto';
import { ACCOUNT_ID } from '../../../common/constants/auth.constant';
import { FindOptionsWhere, Like } from 'typeorm';
import { Menu } from './entities/menu.entity';
import { ResponseMsgKey } from '../../../common/constants/api-response.constant';
import { RequirePermission } from '../../../common/decorators/require-permission.decorator';

@Controller('menu')
export class MenuController {
  constructor(private readonly menuService: MenuService) {}

  @RequirePermission('sys:menu:save')
  @Post('save')
  async save(@Body() body: SaveMenuDto) {
    return await this.menuService.save(body);
  }

  @RequirePermission('sys:menu:find')
  @Get()
  async findAll(
    @Query('name') name?: string,
    @Query(
      'state',
      new ParseBoolPipe({
        exceptionFactory: () => {
          return new Error(ResponseMsgKey.PARAM_ERROR);
        },
        optional: true,
      }),
    )
    state?: boolean,
  ) {
    const where: FindOptionsWhere<Menu> = {
      state,
    };
    if (name) {
      where.name = Like(`%${name}%`);
    }
    return await this.menuService.find({ where });
  }

  @Get()
  async findByAdmin(@Req() request: Request) {
    return await this.menuService.findByAdmin(request[ACCOUNT_ID]);
  }

  @RequirePermission('sys:menu:delete')
  @Delete()
  async delete(@Body('ids') ids: string[]) {
    return await this.menuService.delete(ids);
  }
}
